package com.fit.pages.company;

import java.util.List;

import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;

import com.fit.annotations.AdminAccess;
import com.fit.annotations.UserAccess;
import com.fit.dao.company.CompanyDAO;
import com.fit.entities.Company;

@AdminAccess
public class ManageCompanies {

	@Property
	private List<Company> companies;
	
	@Property
	private Company company;
	
	@Inject
	private CompanyDAO companyDAO;
	
	@Persist
	private String error;
	
	@Persist
	private String confirmation;
	
	void onActivate() {
		companies = companyDAO.findAll();
	}

	@OnEvent(component = "deleteLink")
	Object onDeleteLink(Long id) {
		error = "";
		confirmation="";
		Company c = companyDAO.findById(id);
		if(companyDAO.checkUsers(c)){
			error="You can't delete company associated with some users!";;
			return null;
		}
		if(companyDAO.checkRegistrations(c)){
			error = "You can't delete company associated with some registrations!";
			return null;
		}
		try {
			companyDAO.deleteById(id);
			confirmation = "Company successfully deleted.";
			return null;
		} catch (Exception e) {
			confirmation = "Error deleting company. ";
			return null;
		}	
	}
	
	@OnEvent(component = "ResetConfLink")
	Object onResetConfLink() {
		confirmation="";
		return null;
	}
	
	@OnEvent(component = "ResetErrorLink")
	Object onResetErrorLink() {
		error="";
		return null;
	}
	
	
	public boolean isErrorNotNull(){
		if(error==null || error==""){
			return false;
		}
		return true;
	}
	
	public boolean isConfirmationNotNull(){
		if(confirmation==null || confirmation==""){
			return false;
		}
		return true;
	}

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}

	public String getConfirmation() {
		return confirmation;
	}

	public void setConfirmation(String confirmation) {
		this.confirmation = confirmation;
	}
}
